package com.hanter.android.radlib.compat;


import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

/**
 * PopupWindow弹出兼容
 */
public class MyPopupWindowCompat {

    public static void showAsDropDown(PopupWindow pw, View anchor, int xoff, int yoff) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N &&
                pw.getHeight() == WindowManager.LayoutParams.MATCH_PARENT) {
            int[] location = new int[2];
            anchor.getLocationOnScreen(location);
            int screenHeight = anchor.getResources().getDisplayMetrics().heightPixels;
            pw.setHeight(screenHeight - location[1] - anchor.getHeight() - yoff);
            pw.showAtLocation(anchor, Gravity.NO_GRAVITY, location[0] + xoff,
                    location[1] + anchor.getHeight() + yoff);
        } else {
            pw.showAsDropDown(anchor, xoff, yoff);
        }
    }

    public static void showAsTopCenter(PopupWindow pw, View anchor) {
        int[] location = new int[2];
        anchor.getLocationOnScreen(location);
        pw.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int windowWidth = pw.getContentView().getMeasuredWidth();
        int windowHeight = pw.getContentView().getMeasuredHeight();
        pw.showAtLocation(anchor, Gravity.NO_GRAVITY, location[0] - windowWidth / 2 + anchor.getWidth() / 2 , location[1] - windowHeight);
    }

    public static void dim(PopupWindow window) {
        dim(window, 0.6f);
    }

    public static void dim(PopupWindow window, float dimAmount) {
        WindowManager wm = (WindowManager) window.getContentView().getContext().getSystemService(Context.WINDOW_SERVICE);
        if (wm != null) {
            View parent = window.getContentView().getRootView();
            WindowManager.LayoutParams p = (WindowManager.LayoutParams) parent.getLayoutParams();
            p.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
            p.dimAmount = dimAmount;
            wm.updateViewLayout(parent, p);
        }
    }

}
